import { request } from '@/utils/http'
import type { RouteRecordNormalized } from 'vue-router'
import { getCrudApi } from '@/utils/http/crud.ts'
import { PermissionDto } from '@/api/permission.ts'
import { RoleType } from '@/api/role.ts'

export interface LoginDto {
  username: string | null
  password: string | null
  code: string | null
}

export interface autoLoginDto {
  type: 'oa' | 'weixin' | 'oauth2'
  ticket: 'string'
}

export interface LoginRes {
  accessToken: string
  refreshToken: string
}

export interface UserDto {
  id?: string
  username: string | null
  password?: string
  name?: string | null
  avatar?: string | null
  mobile?: string | null
  disabled?: boolean
  remark?: string | null
  role: RoleType
  createdAt?: string
}

export interface QueryUserDto {
  name?: string | null
  username?: string | null
  mobile?: string | null
  disabled?: boolean
}

export interface UpdatePasswordDto {
  password: string
  newPassword: string
}

export interface UpdateUserInfoDto {
  name?: string | null
  avatar?: string | null
  mobile?: string | null
}

function login(data: LoginDto) {
  return request.post<LoginRes>('/user/login', data)
}

function autoLogin(data: autoLoginDto) {
  return request.post<LoginRes>('/user/auto-login', data)
}

function logout() {
  return request.post<LoginRes>('/user/logout')
}

export function getUserInfo() {
  return request.post<UserDto>('/user/info')
}

export function getPermission() {
  return request.post<PermissionDto[]>('/user/permission')
}

function getMenuList() {
  return request.post<RouteRecordNormalized[]>('/user/menu')
}

function getUserBase() {
  return request.get('/user/base')
}

export function updatePassword(form: UpdatePasswordDto) {
  return request.post('/user/password', form)
}

export function updateUserInfo(form: UpdateUserInfoDto) {
  return request.put<UserDto>('/user/info', form)
}

export function getMeasureStat() {
  return request.get('/user/measures')
}

export function getQuestions() {
  return request.get('/user/questions')
}

const userApi = getCrudApi<UserDto>('user')

export default {
  ...userApi,
  login,
  autoLogin,
  logout,
  getUserInfo,
  getMenuList,
  getUserBase,
}
